from django.shortcuts import render

# Create your views here.

# from fdfs_client.client import Fdfs_client
#
# cli=Fdfs_client(conf_path='utils/fastdfs/client.conf') #连接fastdfs服务器
# file_dict=cli.upload_by_filename('/home/hw/桌面/meiduo_git_huang/front_end_pc/images/banner01.jpg') #上传文件，返回文件信息字典
# #返回的字典数据
# # {'Group name': 'group1',
# # 'Remote file_id': 'group1/M00/00/00/wKi2BWRh9eSANM03AABcalxfbWk739.jpg',
# # 'Status': 'Upload successed.',
# # 'Local file name': '/home/hw/桌面/meiduo_git_huang/front_end_pc/images/banner01.jpg',
# # 'Uploaded size': '23.00KB',
# # 'Storage IP': '192.168.182.5'}
from django.views import View
from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet

from utils.customEncryption import jiami
from utils.goods import get_categories
from apps.contents.models import ContentCategory
class IndexView(View):
    """首页广告"""

    def get(self, request):
        """提供首页广告界面"""
        # 查询商品频道和分类
        categories=get_categories()
        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

        # 渲染模板的上下文
        context = {
            'categories': categories,
            'contents': contents,
        }
        return render(request, 'index.html', context)

class ListView(View):
    """列表页数据展示"""

    def get(self,request,id):
        # 1.拿到参数
        #?page=页码&page_size=总页数&ordering=排序规则
        ordering=request.GET.get('ordering')
        page=request.GET.get('page')
        page_size=request.GET.get('page_size')
        # 2.设置面包屑数据
        from apps.goods.models import GoodsCategory
        from django.http import JsonResponse
        try:
            category=GoodsCategory.objects.get(id=id)
        except Exception:
            return JsonResponse({'code':400,'errmsg':'参数错误'})
        from utils import goods
        breadcrumb=goods.get_breadcrumb(category) #面包屑数据
        # 3.数据库拿数据，排序
        from apps.goods.models import SKU
        skudatas=SKU.objects.filter(category=category,is_launched=True).order_by(ordering)
        # 4.分页
        from django.core.paginator import Paginator
        p=Paginator(skudatas,5) #Paginator(数据集，每页显示多少数据)
        total_page=p.num_pages #总页数
        mylist=[]
        pagesku=p.page(page)
        for sku in pagesku:
            mylist.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })
        # 5.返回数据
        return JsonResponse({
                             'code':0,
                             'errmsg':'ok',
                             'breadcrumb': breadcrumb,
                             'list':mylist,
                             'count':total_page
                            })

class HotGoodsView(View):
    """热销排行数据"""
    def get(self,request,id):
        #1.拿到标题id
        #2.拿数据并且降序
        from apps.goods.models import SKU
        skus=SKU.objects.filter(category_id=id,is_launched=True).order_by('-sales')[:2]
        # 序列化
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id':sku.id,
                'default_image_url':sku.default_image.url,
                'name':sku.name,
                'price':sku.price
            })
        #3.返回数据
        from django.http import JsonResponse
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'hot_skus': hot_skus})

from haystack.views import SearchView
class MySearchView(SearchView):

    def create_response(self):
        #haystack已经自己拿到数据，我们直接拿就完事了
        context = self.get_context()

        datas=context.get('page').object_list #拿到搜索后的数据，
        data_list=[]

        for sku in datas:
            data_list.append({
                'id': sku.object.id,
                'name': sku.object.name,
                'price': sku.object.price,
                'default_image_url': sku.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,
                'count': context['page'].paginator.count
            })

        from django.http import JsonResponse
        return JsonResponse(data_list, safe=False)

from django.http import HttpResponse
class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        from apps.goods import models
        from utils.goods import get_breadcrumb,get_goods_specs
        # 获取当前sku的信息
        try:
            sku = models.SKU.objects.get(id=sku_id)
        except models.SKU.DoesNotExist:
            return HttpResponse('没有这个商品！')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)
        # 查询SKU规格信息
        goods_specs=get_goods_specs(sku)

        # 渲染页面
        context = {
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sku':sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)


class DetailVisitView(View):
    """详情页分类商品访问量"""

    def post(self,request,category_id):
        # 1.拿到参数判断是否有该分类
        from apps.goods.models import GoodsCategory
        from django.http import JsonResponse
        from apps.goods.models import GoodsVisitCount
        try:
            category=GoodsCategory.objects.get(id=category_id)
        except Exception:
            return JsonResponse({'code':400,'errmsg':'没有该类商品'})
        # 2.有查看是否是今天第一次访问
        import datetime
        day=datetime.date.today()
        try:
            visitCount=GoodsVisitCount.objects.get(category=category,date=day)
        except Exception:
            # 3.第一次添加，
            GoodsVisitCount.objects.create(category=category,count=1,date=day)
        else:
            # 不是第一次就为增加
            visitCount.count+=1
            visitCount.save()
        # 4.返回数据
        return JsonResponse({'code':0,'errmsg':'ok'})



#商品评论 增删改查
from apps.goods.models import GoodsComment,SKU
from rest_framework import serializers
class GoodsCommentModelSerializer(ModelSerializer):
    username=serializers.StringRelatedField(source='user.username')

    """商品评论序列化器"""
    class Meta:
        model=GoodsComment
        fields=('comment','username','update_time','user','order','sku','spu')
        read_only_fields = ('update_time', 'username', )
        write_only_fields=('comment','user','order','sku','spu')

from apps.orders.models import OrderGoods,OrderInfo
from rest_framework.response import Response
from rest_framework import status
class GoodsCommentModelViewSet(ModelViewSet):
    """评论增删改查"""
    serializer_class = GoodsCommentModelSerializer
    authentication_classes = []
    def get_queryset(self):
        self.request.query_params.get('skuId')
        spu_id=SKU.objects.get(id=1).spu.id
        return GoodsComment.objects.filter(spu_id=spu_id)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        #给用户名加密
        comments=serializer.data
        for item in comments:
            item['username']=item['username'][:3]+'****'+item['username'][-4:]

        return Response({'comments':serializer.data})

    def create(self, request, *args, **kwargs):
        orderId = request.data.get('orderId')
        #查看评论数是否大于3
        if len(GoodsComment.objects.filter(order_id=orderId)) >=3:
            return Response({'status': '202'}, status=status.HTTP_201_CREATED)
        #拿前端数据
        skuId=request.data.get('skuId')
        comment=request.data.get('comment')
        spuId=SKU.objects.get(id=skuId).spu_id
        userId=jiami(expires_in=60*60*12*14).decrypt(request.data.get('key'))
        data={
            'comment':comment,
            'user':userId,
            'order':orderId,
            'sku':skuId,
            'spu':spuId
        }

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        #订单商品评论数=3，修改订单状态
        if len(GoodsComment.objects.filter(order_id=orderId)) == len(OrderGoods.objects.filter(order_id=orderId))*3:
            OrderInfo.objects.filter(order_id=orderId).update(status=OrderInfo.ORDER_STATUS_ENUM["FINISHED"])

        return Response({'status':'201'}, status=status.HTTP_201_CREATED, headers=headers)







